//
//  APIService.swift
//  GoAbroad
//
//  Created by Pink Snow on 2025/5/7.
//

import UIKit
import Moya
struct DownloadedImageResult {
    let image: UIImage
    let fileURL: URL
    let progress: Double
}
enum APIService {
    case login(username: String, password: String)
    case register(email : String , passwd : String)
    case uploadUser(user_id : String ,email : String ,from_login : String? = "" ,avatar : String? = ""  , nick_name : String? = "")
    case uploadImage(image : UIImage?,description : String?,color_type: String?,size: String? = "1:1",img_type : String? = "1" )
    case getCurrentUser
    case tasks(taskId:String)
    case getSubscribplans
    case getSubPlans
    case fetchUser(id: Int)
    case downloadImage(url : String)
    case applePayVerify(receipt : String , orderid: String)
    case appPayOrder(code: String)
    case setUserInfo(userid:String,email:String,from:String)
    case appleLogin(client : String,token:String)
}

extension APIService: TargetType {
    var baseURL: URL {
        switch self {
        case let .downloadImage(url):
            return URL(string : url)!
        case  .applePayVerify:
            return URL(string: "https://tattoo.ghiblitattoo.com")!
        default :
            return URL(string: "https://tattoo.ghiblitattoo.com")!
        }
        ///local : http://192.168.0.205:9501
        /// service : https://cartoon.GhibliMagicMaker.com
        
    }
    
    var path: String {
        switch self {
        case .login:
            return "/auth/login"
        case .fetchUser(let id):
            return "/user/\(id)"
        case .register:
            return ""
            ///上传图片  图生图 文生图
        case .uploadImage:
            return "/api/ghiblio/tattoo"
            ///上传用户信息
        case .uploadUser:
            return "/auth/system/setUserInfo"
            ///获取用户信息
        case .getCurrentUser :
            return "/api/system/getCurrentUser"
            ///获取文件生成结果
        case  .tasks(let  task):
            return "/api/card/getTaskInfo/\(task)"
        case .getSubscribplans:
            return "/api/order/getSubscribelans"
        case .getSubPlans:
            return "/api/order/getSubPlans"
        case .downloadImage:
            return ""
        case .applePayVerify:
            return "/api/apple/iapPayVerify"
        case .appPayOrder:
            return "/api/apple/iapPayOrder"
        case .setUserInfo:
            return "/auth/system/setUserInfo"
        case .appleLogin:
            return "/auth/system/appleLogin"
        }
    }
    
    var method: Moya.Method {
        switch self {
        case .login:
            return .post
        case .fetchUser:
            return .get
        case .getCurrentUser:
            return .get
        case .tasks:
            return.get
        case .getSubscribplans:
            return .get
        case .downloadImage:
            return .get
        default :
            return .post
        }
    }
    
    var task: Task {
        switch self {
        case let .login(username, password):
            return .requestParameters(parameters: ["username": username, "password": password],encoding: URLEncoding.httpBody)
        case .fetchUser:
            return .requestPlain
        case let .register(email, password) :
            
            return .requestParameters(parameters: ["email" : email,"password":password], encoding: URLEncoding.httpBody)
        case let .uploadUser(userid,  email,  fromlogin, avatar,  name):
            let fields = ["user_id":userid,"email":email,"from_login":fromlogin,"avatar":avatar,"nick_name":name]
            let formData = makeMultipartFormData(from: fields)
            return .uploadMultipart(formData)
            //            return .requestParameters(parameters: ["user_id":userid,"email":email,"from_login":fromlogin ?? "","avatar":avatar ?? "","nick_name":name ?? ""], encoding: URLEncoding.httpBody)
        case let .uploadImage(image: image,description: des, color_type: color, size: size, img_type: type):
            let formData :  [MultipartFormData] = makeUploadFormData(image: image, fields: [
                "description": des,
                "color_type": color,
                "size": size ?? "1:1",
                "img_type": type ?? "1"
            ])
            return .uploadMultipart(formData)
        case  .getCurrentUser:
            return .requestPlain
        case   .tasks:
            return .requestPlain
        case .getSubscribplans:
            return .requestPlain
        case .getSubPlans:
            return .requestPlain
        case .downloadImage:
            return .requestPlain
        case let  .applePayVerify(receipt,order):
            let fields  = ["receipt_data":receipt,"order_id":order]
            let formData = makeMultipartFormData(from: fields)
            return .uploadMultipart(formData)
        case let  .appPayOrder(code):
            let fields  = ["code":code]
            let formData = makeMultipartFormData(from: fields)
            return .uploadMultipart(formData)
        case let .setUserInfo(userid, email, from):
            let fields = ["user_id":userid,"email":email,"from_login":from]
            let formData = makeMultipartFormData(from: fields)
            return .uploadMultipart(formData)
        case let .appleLogin(client, token):
            let fields = ["clientUser":client,"identifyToken":token]
            let formData = makeMultipartFormData(from: fields)
            return .uploadMultipart(formData)
        }
    }
    var headers: [String: String]? {
        switch self {
        case .tasks:
            return ["Content-Type":"application/json"]
        case .downloadImage:
            return nil
        default :
            return ["Content-Type":"multipart/form-data"]
        }
        
    }
    
    var sampleData: Data {
        return Data()
    }
    
    func makeUploadFormData(
        image: UIImage?,
        imageFieldName: String = "file",
        imageFileName: String = "file.jpeg",
        fields: [String: String?]?
    ) -> [MultipartFormData] {
        var formData: [MultipartFormData] = []
        
        // ✅ 添加图片（可选）
        if let img = image,
           let imageData = img.jpegData(compressionQuality: 0.8) {
            let imagePart = MultipartFormData(
                provider: .data(imageData),
                name: imageFieldName,
                fileName: imageFileName,
                mimeType: "image/jpeg"
            )
            formData.append(imagePart)
        }
        if let field = fields {
            // ✅ 添加其他字段
            for (key, value) in field {
                if let actual = value {
                    let part = MultipartFormData(
                        provider: .data(actual.data(using: .utf8)!),
                        name: key
                    )
                    formData.append(part)
                }
            }
        }
        
        
        return formData
    }
    func makeMultipartFormData(from fields: [String: String?]) -> [MultipartFormData] {
        return fields.map {
            MultipartFormData(
                provider: .data($0.value!.data(using: .utf8)!),
                name: $0.key
            )
        }
    }
    
    
    
}


